import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/festival.dart';
import 'package:geomancy/models/festival_list_model.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_shadow_text.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/stroke_text.dart';
import 'package:go_router/go_router.dart';
import 'package:lunar/lunar.dart';

class CalendarFestivalPage extends StatefulWidget {
  const CalendarFestivalPage({super.key});

  @override
  State<CalendarFestivalPage> createState() => _CalendarFestivalPageState();
}

class _CalendarFestivalPageState extends State<CalendarFestivalPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  int tabIndex = 0;
  List<FestivalItemModel> festivalList = [];
  List<FestivalItemModel> festivalDisplayList = [];
  final int year = DateTime.now().month > 11 ? DateTime.now().year+1 : DateTime.now().year;
  List<Holiday> holidays = [];

  @override
  void initState() {
    super.initState();
    get24FestivalList();
    filterLegalHolidays();
  }

  /// 过滤法定节假日
  void filterLegalHolidays() {
    // 从 HolidayUtil 获取原始节假日数据
    List<Holiday> originalHolidays = HolidayUtil.getHolidays(year.toString());
    
    // 需要匹配的节日名称
    final targetFestivals = [
      '元旦节',
      '春节',
      '清明节',
      '劳动节',
      '端午节',
      '中秋节',
      '国庆节',
      '国庆中秋',
      '抗战胜利日'
    ];
    
    // 直接过滤出目标节日且日期相同的记录
    holidays = originalHolidays.where((holiday) {
      // 获取节日信息
      String firstDate = holiday.getDay();
      String festivalName = holiday.getName();
      String lastDate = holiday.getTarget();
      
      // 检查是否是目标节日、不是调休日、且前后日期相同
      return targetFestivals.any((festival) => 
          festivalName.contains(festival)) && 
          !holiday.isWork() && 
          firstDate == lastDate;
    }).toList();
  }

  ///获取节气列表
  Future get24FestivalList() async {
    final list = await FestivalAPI.get24FestivalList(context);
    for (int i = 0; i < list.length; i ++) {
      // if (list[i].pubDate)
    }
    setState(() {
      festivalList = sortFestivalsByDate(list);
      festivalDisplayList = List.from(festivalList)..removeAt(0);
    });
  }

  /// 按日期排序节日列表
  /// 使用pubYear和"X月X日"格式进行排序
  List<FestivalItemModel> sortFestivalsByDate(List<FestivalItemModel> list) {
    // 获取今天的日期，设置时分秒为0
    final today = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);

    // 先过滤出日期大于或等于今天的节日
    list = list.where((item) {
      final aYear = int.tryParse(item.pubYear ?? '') ?? today.year;
      DateTime? aDate = _parseDate(item.pubDate, aYear);
      if (aDate == null) return false;
      // 保留今天及以后（包括今天）的节日，忽略时分秒
      return aDate.isAfter(today) || aDate.isAtSameMomentAs(today);
    }).toList();

    list.sort((a, b) {
      // 先比较年份
      final aYear = int.tryParse(a.pubYear ?? '') ?? DateTime.now().year;
      final bYear = int.tryParse(b.pubYear ?? '') ?? DateTime.now().year;
      
      if (aYear != bYear) {
        return aYear.compareTo(bYear);
      }
      
      // 年份相同时，比较月日
      DateTime? aDate = _parseDate(a.pubDate, aYear);
      DateTime? bDate = _parseDate(b.pubDate, bYear);
      
      // 如果转换失败，将null值排到最后
      if (aDate == null) return 1;
      if (bDate == null) return -1;
      
      return aDate.compareTo(bDate);
    });
    
    return list;
  }

  /// 将"X月X日"格式转换为DateTime对象
  /// 如: "2月3日" -> DateTime(year, 2, 3)
  DateTime? _parseDate(String? dateStr, int year) {
    if (dateStr == null || dateStr.isEmpty) return null;
    
    try {
      // 提取月份和日期
      final parts = dateStr.replaceAll('月', '-').replaceAll('日', '').split('-');
      if (parts.length != 2) return null;
      
      final month = int.parse(parts[0]);
      final day = int.parse(parts[1]);
      
      return DateTime(year, month, day);
    } catch (e) {
      return null;
    }
  }

  void goToDetailPage(FestivalItemModel item) {
    ///需要将中文的节气转化成拼音
    context.push('/festival_desc', extra: {
      "festival": item,
    });
  }

  ///container样式
  BoxDecoration containerStyle() {
    return BoxDecoration(
        color: ColorStyle.themeLightColor,
        border: Border.all(width: 5.w, color: ColorStyle.borderColor),
        borderRadius: BorderRadius.all(Radius.circular(60.w))
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView(
      physics: const ClampingScrollPhysics(),
      padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 40.w),
      children: [
        ///顶部tab
        Wrap(
          alignment: WrapAlignment.center,
          spacing: 6.w,
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  tabIndex = 0;
                });
              },
              child: Container(
                width: 252.w,
                height: 80.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: tabIndex == 0 ? ColorStyle.themeColor : ColorStyle.themeLightColor,
                    border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(40.w),
                      bottomLeft: Radius.circular(40.w),
                      topRight: Radius.circular(15.w),
                      bottomRight: Radius.circular(15.w),
                    )
                ),
                child: StrokeText(txt: '二十四节气', color: ColorStyle.themeLightColor),
              ),
            ),
            GestureDetector(
              onTap: () {
                setState(() {
                  tabIndex = 1;
                });
              },
              child: Container(
                width: 252.w,
                height: 80.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: tabIndex == 1 ? ColorStyle.themeColor : ColorStyle.themeLightColor,
                    border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(40.w),
                      bottomRight: Radius.circular(40.w),
                      topLeft: Radius.circular(15.w),
                      bottomLeft: Radius.circular(15.w),
                    )
                ),
                child: StrokeText(txt: '法定节假日', color: ColorStyle.themeLightColor),
              ),
            )
          ],
        ),
        SizedBox(height: 20.w),
        if (tabIndex == 0)
          Stack(
            children: [
              ///这里显示剩余节气的列表
              Container(
                width: 670.w,
                padding: EdgeInsets.only(top: 700.w, left: 40.w, right: 40.w),
                decoration: containerStyle(),
                child: Column(
                  children: festivalDisplayList.asMap().keys.map((index) {
                    final item = festivalDisplayList[index];
                    final dateList = item.pubDate?.split('月') ?? [];
                    final month = dateList[0].padLeft(2, '0');
                    final day = dateList[1].split('日')[0].padLeft(2, '0');
                    return GestureDetector(
                      onTap: () {
                        goToDetailPage(festivalDisplayList[index]);
                      },
                      child: Container(
                        key: ValueKey(index),
                        height: 120.w,
                        decoration: BoxDecoration(
                          border: index < festivalDisplayList.length - 1
                            ? Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                            : null
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Row(
                              children: [
                                Expanded(child: CommonText(txt: '${item.name}', weight: FontWeight.bold)),
                                CommonText(txt: Utils.getDaysFromNow('${item.pubYear}-$month-$day'), fontSize: 24.sp),
                                SizedBox(width: 10.w),
                                Image.asset('assets/icons/icon_arrow_right.png', width: 10.w)
                              ],
                            ),
                            Row(
                              children: [
                                CommonText(txt: '${item.pubDate}', fontSize: 24.sp),
                                SizedBox(width: 20.w),
                                CommonText(txt: '农历${item.priDate}', fontSize: 24.sp),
                              ],
                            ),
                          ],
                        ),
                      ),
                    );
                  }).toList()
                ),
              ),
              ///这里显示第一个节气的大图
              if (festivalList.isNotEmpty)
                Container(
                  height: 705.w,
                  decoration: containerStyle(),
                  child: Stack(
                    children: [
                      Positioned.fill(
                        child: ClipRRect(
                          borderRadius: BorderRadius.all(Radius.circular(55.w)),
                          child: Image.asset('assets/festivals/${festivalList[0].name}.jpg', fit: BoxFit.fill),
                        )
                      ),
                      Positioned(
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: GestureDetector(
                          onTap: () {
                            goToDetailPage(festivalList[0]);
                          },
                          child: Container(
                            height: 130.w,
                            decoration: BoxDecoration(
                                color: ColorStyle.themeLightColor.withOpacity(0.1),
                                borderRadius: BorderRadius.all(Radius.circular(55.w))
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.all(Radius.circular(55.w)),
                              child: BackdropFilter(
                                filter: ImageFilter.blur(
                                  sigmaX: 5, // 横向模糊程度
                                  sigmaY: 5, // 纵向模糊程度
                                ),
                                child: Container(
                                  color: Colors.transparent, // 保持透明，显示模糊效果
                                  padding: EdgeInsets.symmetric(horizontal: 60.w),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Row(
                                        children: [
                                          Container(
                                            margin: EdgeInsets.only(bottom: 6.w, right: 26.w),
                                            child: CommonShadowTextWidget(txt: '${festivalList[0].name}', fontSize: 30.sp),
                                          ),
                                          CommonText(txt: '${festivalList[0].pubDate}', fontSize: 24.sp),
                                          Container(
                                            width: 2.w,
                                            height: 21.w,
                                            margin: EdgeInsets.symmetric(horizontal: 6.w),
                                            decoration: BoxDecoration(
                                                color: ColorStyle.themeColor,
                                                borderRadius: BorderRadius.all(Radius.circular(1.w))
                                            ),
                                          ),
                                          Expanded(child: CommonText(txt: '农历${festivalList[0].priDate}', fontSize: 24.sp),),
                                          Container(
                                            width: 80.w,
                                            height: 36.w,
                                            alignment: Alignment.center,
                                            decoration: BoxDecoration(
                                                color: ColorStyle.themeColor,
                                                borderRadius: BorderRadius.all(Radius.circular(18.w))
                                            ),
                                            child: CommonText(txt: '查看', fontSize: 24.sp),
                                          )
                                        ],
                                      ),
                                      Text('${festivalList[0].des?.replaceAll('<p>', '').replaceAll('</p>', '')}', overflow: TextOverflow.ellipsis, maxLines: 1, style: TextStyle(fontSize: 24.sp, color: ColorStyle.textColor))
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        )
                      )
                    ],
                  ),
                ),
            ],
          )
        else
          Container(
            padding: EdgeInsets.fromLTRB(35.w, 40.w, 35.w, 0),
            decoration: containerStyle(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                CommonShadowTextWidget(txt: '$year年', fontSize: 30.sp),
                SizedBox(height: 12.w),
                Column(
                  children: holidays.asMap().keys.map((index) {
                    final item = holidays[index];
                    final dateList = item.getDay().split('-');
                    final date = '${dateList[1]}.${dateList[2]}';
                    return Container(
                      key: ValueKey(index),
                      height: 120.w,
                      padding: EdgeInsets.only(left: 12.w),
                      decoration: BoxDecoration(
                          border: index < holidays.length - 1 ? Border(
                              bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor)
                          ) : null
                      ),
                      child: Row(
                        children: [
                          SizedBox(
                            width: 90.w,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Text(date, style: TextStyle(fontSize: 30.sp, color: ColorStyle.red)),
                                const CommonText(txt: '周三')
                              ],
                            ),
                          ),
                          Container(
                            width: 2.w,
                            height: 66.w,
                            margin: EdgeInsets.only(left: 16.w, right: 42.w),
                            decoration: BoxDecoration(
                                color: ColorStyle.borderColor,
                                borderRadius: BorderRadius.all(Radius.circular(1.w))
                            ),
                          ),
                          Expanded(child: CommonText(txt: item.getName(), weight: FontWeight.bold)),
                          CommonText(txt: Utils.getDaysFromNow(item.getDay()))
                        ],
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
          )
      ],
    );
  }
}
